// DraggableResizableWidget.tsx
import React, { useState } from 'react';
import Draggable, { type DraggableData } from 'react-draggable';
import { Resizable } from 'react-resizable';
import type { GridWidget, GridConfig } from './types';

interface Props {
  widget: GridWidget;
  gridConfig: GridConfig;
  onUpdate: (widget: GridWidget) => void;
}

const DraggableResizableWidget: React.FC<Props> = ({ widget, gridConfig, onUpdate }) => {
  const [isRotating, setIsRotating] = useState(false);

  // 处理拖拽结束：更新位置（对齐网格）
  const handleDragStop = (e: React.MouseEvent, data: DraggableData) => {
    const snappedX = Math.round((widget.x + data.x) / gridConfig.cellSize) * gridConfig.cellSize;
    const snappedY = Math.round((widget.y + data.y) / gridConfig.cellSize) * gridConfig.cellSize;
    onUpdate({ ...widget, x: snappedX, y: snappedY });
  };

  // 处理缩放结束：更新尺寸（对齐网格）
  const handleResize = (_: React.SyntheticEvent, _dir: [number, number], ref: HTMLDivElement | null) => {
    if (!ref) return;
    const snappedWidth = Math.round(ref.offsetWidth / gridConfig.cellSize) * gridConfig.cellSize;
    const snappedHeight = Math.round(ref.offsetHeight / gridConfig.cellSize) * gridConfig.cellSize;
    onUpdate({ ...widget, width: snappedWidth, height: snappedHeight });
  };

  // 处理旋转：每次点击旋转 90 度
  const handleRotate = () => {
    const newRotation = (widget.rotation + 90) % 360;
    onUpdate({ ...widget, rotation: newRotation });
  };

  return (
    <Draggable
      nodeRef={(ref) => ref as HTMLDivElement}
      position={{ x: widget.x, y: widget.y }} // 基于网格容器的绝对位置
      onStop={handleDragStop}
      disabled={isRotating} // 旋转时禁用拖拽
    >
      <Resizable
        width={widget.width}
        height={widget.height}
        minConstraints={[gridConfig.cellSize * 2, gridConfig.cellSize * 2]} // 最小尺寸（2个网格单元）
        maxConstraints={[gridConfig.cellSize * 10, gridConfig.cellSize * 10]} // 最大尺寸
        onResize={handleResize}
        handles={['se', 'sw', 'ne', 'nw', 'e', 'w', 'n', 's']} // 八个方向缩放
      >
        <div
          style={{
            width: '100%',
            height: '100%',
            padding: 16,
            border: '1px solid #2962ff',
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            borderRadius: 4,
            transform: `rotate(${widget.rotation}deg)`, // 应用旋转
            transformOrigin: 'center', // 基于中心旋转
            position: 'relative',
            zIndex: widget.zIndex,
          }}
        >
          {/* 组件内容 */}
          <h3>{widget.name}</h3>
          <p>类型：{widget.type}</p>

          {/* 旋转控制按钮 */}
          <button
            onClick={handleRotate}
            style={{
              position: 'absolute',
              top: 8,
              right: 8,
              padding: 4,
              backgroundColor: '#2962ff',
              color: 'white',
              border: 'none',
              borderRadius: 4,
              cursor: 'pointer',
            }}
          >
            旋转
          </button>

          {/* 缩放控制点样式（覆盖默认样式） */}
          <style jsx global>{`
            .react-resizable-handle {
              background-color: #2962ff;
              border: 1px solid white;
              width: 12px;
              height: 12px;
            }
          `}</style>
        </div>
      </Resizable>
    </Draggable>
  );
};

export default DraggableResizableWidget;
